package com.shujia.windowApply;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

public class CountWindowApply {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> linesDS = env.socketTextStream("hadoop102", 8888);

        DataStream<Tuple2<String, Integer>> kvDS = linesDS
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        //分组
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(kv -> kv.f0);


        /*
         * countWindow：每隔几条数据计算一次
         * .countWindow(10)：滚动的统计窗口
         * .countWindow(10, 2)：滑动的统计窗口
         */
        //划分窗口
        WindowedStream<Tuple2<String, Integer>, String, GlobalWindow> windowDS = keyByDS
                //每隔两条数据计算最近10条数据
                .countWindow(10, 1);

        DataStream<Tuple2<String, Integer>> countDS = windowDS.sum(1);

        countDS.print();

        env.execute();
    }
}
